/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.hamacekj.dotaznikklient;

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;


/**
 * Otázka s odpovědí ano/ne.
 * @author Jan Hamáček
 */
public class YNQuestion extends Question {

    public YNQuestion(BufferedWriter out, QuestionsQueue queue) {
        super(out, queue);
        question = new StringBuilder();
    }
    
    @Override
    public String toText(){
        throw new UnsupportedOperationException();
    }

    @Override
    public void invokeGUIAndSendReply() {
        try{
            SwingUtilities.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    createAndShowGUI();
                }
            });
        }catch(InterruptedException | InvocationTargetException e){}
    }

    @Override
    public void fromFirstLine(String firstLine) throws ProtocolException {
        try{
            String[] splitted = firstLine.split(" ");
            if(!"ASK".equals(splitted[0]) || !"YN".equals(splitted[1])){
                throw new ProtocolException();
            }
            this.id = Integer.parseInt(splitted[2]);
        }catch(IndexOutOfBoundsException | NumberFormatException e){
            throw new ProtocolException();
        }
    }

    @Override
    public void addParam(String dataLine) throws ProtocolException {
        String[] splitted = dataLine.split(" ", 2);
        // rozhoduje o jaky typ parametru jde
        switch(splitted[0]){
            case "MSG":
                if(question.length() != 0){
                    question.append("<br>");
                }
                question.append(splitted[1]);
                break;
        }
    }

    @Override
    public void cancel() {
        if(frame != null){
            frame.setVisible(false);
            frame = null;
        }
    }
    
    private void createAndShowGUI(){
        frame = new JFrame("Otázka");
        Container root = frame.getContentPane();
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        root.setLayout(new GridBagLayout());
        if (this.question.length() == 0){
            this.question.append("Odpovězte na otázku");
        }
        JLabel label = new JLabel("<html>"+this.question.toString()+"</html>");
        label.setVerticalAlignment(JLabel.TOP);
        JButton yes = new JButton("Ano");
        JButton no = new JButton("Ne");
        yes.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Thread t = new ReplyThread('Y');
                t.start();
                frame.setVisible(false);
            }
        });
        no.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Thread t = new ReplyThread('N');
                frame.setVisible(false);
                // spoustim vlakno na odpoved a zavolani dalsi otazky.
                // Ted musi byt predchozi otazka zavrena, jinak by se nova nespustila
                t.start();
            }
        });
        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(10, 10, 10, 10);
        c.anchor = GridBagConstraints.FIRST_LINE_START;
        c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.fill = GridBagConstraints.BOTH;
        c.weightx = 1;
        c.weighty = 1;
        root.add(label, c);
        c.gridwidth = 1; c.gridy = 1; c.weighty = 0; c.weightx = 1;
        c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.EAST;
        root.add(yes, c);
        c.gridx = 1; c.weightx = 0;
        root.add(no, c);
        frame.pack();
        frame.setAlwaysOnTop(true);
        frame.setVisible(true);
    }

    @Override
    public boolean isDisplayed() {
        if(frame == null){
            return false;
        }
        return frame.isVisible();
    }
    
    private class ReplyThread extends Thread{
        char answer;

        public ReplyThread(char answer) {
            this.answer = answer;
        }
        
        @Override
        public void run(){
            unfinished.runNext();
            try{
                out.write("REPLY YN "+id+" "+answer);
                out.newLine();
                out.flush();
            }catch(IOException e){
                // WARNING: tady nemam zpusob jak oznamit chybu. Nechci obtezovat uzivatele, mel bych logovat.
                // Pokud to chci oznamit do GUI, musim thread predelat na swingWorker
            }
        }
    }
    
    private StringBuilder question;
    private JFrame frame = null;
}
